package com.caishi.lkx.user.api;

import cn.hutool.core.util.StrUtil;
import com.caishi.lkx.common.AdminBaseApi;
import com.caishi.lkx.common.role.Role;
import com.caishi.lkx.user.model.ActionRoleModel;
import com.caishi.lkx.user.model.UserModel;
import com.caishi.lkx.user.service.IActionRoleService;
import com.caishi.lkx.user.service.IUserService;
import com.zzw.common.Wrappers;
import com.zzw.common.entity.impl.BaseEntity;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by keray
 * date:2021/4/13 3:10 下午
 */
@RestController
@RequestMapping("/user/cu/auth/role")
public class ActionRoleApi extends AdminBaseApi<IActionRoleService, ActionRoleModel, String> {
    @Resource
    private IActionRoleService actionRoleService;

    @Resource
    private IUserService<UserModel> userService;

    @Override
    public IActionRoleService loadService() {
        return actionRoleService;
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/update")
    public ActionRoleModel add(@RequestBody ActionRoleModel entity) {
        actionRoleService.insert(entity);
        actionRoleService.addAction(entity.getId(), entity.getActionCodes());
        return entity;
    }


    @PutMapping("/update")
    public ActionRoleModel update(@RequestBody ActionRoleModel entity) {
        actionRoleService.update(entity);
        actionRoleService.addAction(entity.getId(), entity.getActionCodes());
        return entity;
    }


    @GetMapping("/current")
    public List<String> currentUserAction() {

        return actionRoleService.selectUserActionCode(userContext.currentUserId());
    }

    @GetMapping("/current-routers")
    public Object currentVueAdminRouters() {
        return Collections.emptyList();
    }

    @GetMapping("/s-list")
    public Collection<ActionRoleModel> list(@ModelAttribute ActionRoleModel searchModel,
                                            @RequestParam(defaultValue = "10") Integer size,
                                            @RequestParam(defaultValue = "false") Boolean searchCount
    ) {
        int userRoleLevel = actionRoleService.selectUserMaxRoleLevel(userContext.currentUserId());
        List<ActionRoleModel> system = Arrays.stream(Role.values())
                .map(v -> {
                    ActionRoleModel model = new ActionRoleModel();
                    model.setId(v.name());
                    model.setName(v.getDesc());
                    model.setSystem(true);
                    model.setRemark("系统配置，前端只能配置action");
                    return model;
                }).filter(v -> {
                    if (StrUtil.isNotBlank(searchModel.getName()) && StrUtil.isNotBlank(searchModel.getId())) {
                        return v.getName().contains(searchModel.getName()) && searchModel.getId().equals(v.getId());
                    } else if (StrUtil.isNotBlank(searchModel.getName())) {
                        return v.getName().contains(searchModel.getName());
                    } else if (StrUtil.isNotBlank(searchModel.getId())) {
                        return searchModel.getId().equals(v.getId());
                    }
                    return true;
                }).collect(Collectors.toList());
        system.addAll
                (actionRoleService.selectList(Wrappers.<ActionRoleModel>lambdaQuery()
                        .like(StrUtil.isNotBlank(searchModel.getName()), ActionRoleModel::getName, searchModel.getName())
                        .eq(StrUtil.isNotBlank(searchModel.getId()), BaseEntity::getId, searchModel.getId())
                        .last("limit " + (size - system.size()))
                ));
        if (searchCount) {
            return system.parallelStream()
                    .peek(v -> v.setActionCount(actionRoleService.roleHaveActionCount(v.getId())))
                    .collect(Collectors.toList());
        }
        return system;
    }
    @GetMapping("/s-list-any")
    public Collection<ActionRoleModel> list(@ModelAttribute ActionRoleModel searchModel){
        return actionRoleService.selectList(Wrappers.<ActionRoleModel>lambdaQuery()
                        .eq(searchModel.getShowLevel() != null, ActionRoleModel::getShowLevel, searchModel.getShowLevel())
                .eq(StrUtil.isNotBlank(searchModel.getId()), BaseEntity::getId, searchModel.getId())
        );
    }

    @GetMapping("/actions/{roleCode}")
    public List<String> roleActions(@PathVariable String roleCode) {
        return actionRoleService.roleActionCodes(roleCode);
    }

    @PostMapping("/details")
    public List<ActionRoleModel> details(@RequestParam List<String> ids) {
        List<String> dataIds = new LinkedList<>();
        List<ActionRoleModel> system = ids.stream().map(id -> {
            try {
                Role r = Role.valueOf(id);
                 return actionRoleService.code2Role(r.name());
            }catch (Exception e) {
                dataIds.add(id);
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        system.addAll(actionRoleService.selectBatchIds(dataIds));
        return system;
    }

    @PostMapping("/add-actions")
    public void roleAddAction(@RequestParam String roleCode,
                              @RequestParam List<String> actionIds
    ) {
        actionRoleService.addAction(roleCode, actionIds);
    }

}
